package de.ars.client.items;

import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import de.ars.client.animator.IAnimationEventListener;
import de.ars.client.items.animators.BrowserAnimator;
import de.ars.client.items.elements.AbstractItem;
import de.ars.client.items.elements.ListItem;
import de.ars.client.paintSystems.StringPainter;
import de.ars.client.screens.MainScreen;

public abstract class AbstractBrowser extends AbstractSlideItem
{
	static String dirUp = "..";
	static Vector lstDir = null;
	
	private String currDirName = null;
	private String currFileName = null;
	
	private int dirState = 0;
	private static final int STATE_CLOSE = 0;
	private static final int STATE_NEXT_DIR = 1;
	private static final int STATE_SELECTED_FILE = 2;
	
	public AbstractBrowser(int _width, int _height, MainScreen _parent, StringPainter _stringPainter)
	{
		super(_width,_height,_parent,_stringPainter);

    	this.animator = new BrowserAnimator(this);
        this.animator.createNewAnimationPoint(this.layout.getAddPersonClosePos());
        this.animator.createNewAnimationPoint(this.layout.getAddPersonCloseSize());
        this.animator.createNewAnimationPoint(this.layout.getAddPersonCloseTextPos());
        this.animator.setLayout(this.layout);
        
        updateFileList();
	}
	
	public void updateFileList()
	{
		this.entryItems = new Vector();
		if (currDirName == null || "".equals(currDirName))
		{
			getRootDirs();
			Enumeration enumer = lstDir.elements();
			while (enumer.hasMoreElements()) 
				this.entryItems.addElement(new ListItem(this.stringPainter,(String)enumer.nextElement()));
		}
		else
		{
			getFileList(this.currDirName);
			Enumeration enumer = lstDir.elements();
			while (enumer.hasMoreElements()) 
				this.entryItems.addElement(new ListItem(this.stringPainter,(String)enumer.nextElement()));
		}
	}
	
	public boolean keyPressed(int _key)
	{
		if (isOpen())
		{
			AbstractItem tempItem = ((AbstractItem)this.entryItems.elementAt(this.selectedItemIndex));
			switch(_key)
	    	{
		    	case -1:
					if(this.selectedItemIndex > 0)
					{
						this.animationType = ANIMATION_SCROLL_UP;
		                ((BrowserAnimator)this.animator).animateScrollUp(tempItem.getHeight());
		                this.selectedItemIndex--;
					}				
					return true;
				case -2:
					if(this.selectedItemIndex < this.entryItems.size()-1)
					{
						this.animationType = ANIMATION_SCROLL_DOWN;
		                ((BrowserAnimator)this.animator).animateScrollDown(tempItem.getHeight());
		                this.selectedItemIndex++;
					}
				return true;
	    		case -5:
	    			selectDirOrFile();  			
	    			return true;
	    		case -6:
	    			dirState = STATE_CLOSE;
	    			close();
	    			return true;
	    	}
		}
		return false;
	}
	
	public void selectDirOrFile()
	{
		String newDir = ((AbstractItem)this.entryItems.elementAt(this.selectedItemIndex)).getText();
		if (newDir.equals(dirUp))
		{
			currDirName = currDirName.substring(0,currDirName.length()-2);
			currDirName = currDirName.substring(0,currDirName.lastIndexOf('/') +1);
			dirState = STATE_NEXT_DIR;
			close();
		}
		else if (newDir.charAt(newDir.length()-1) == '/')
		{
			if (currDirName == null)
				currDirName = "";
			currDirName += newDir;
			dirState = STATE_NEXT_DIR;
			close();
		}
		else
		{
			currFileName = newDir;
			dirState = STATE_SELECTED_FILE;
			close();
		}
	}
	
	private static void getRootDirs () {
		Enumeration enumRoots = FileSystemRegistry.listRoots();
		lstDir = new Vector();
		while (enumRoots.hasMoreElements()) {
			String root = (String)enumRoots.nextElement();
			lstDir.addElement(root); // Directory image instead of null
		}
	}
	
	private void getFileList(String dir) {
		String fileName = null;
		Enumeration enumList;
		FileConnection fc = null;
		try {
			fc = (FileConnection)Connector.open("file:///"+dir);
			enumList = fc.list("*", true);
			lstDir=new Vector();
			lstDir.addElement(".."); //arrow up
			while (enumList.hasMoreElements()) {
				fileName = (String)enumList.nextElement();
				fc = (FileConnection)Connector.open("file:///"+dir+"/"+fileName);
				lstDir.addElement(fileName); // fc.isDirectory()?dirImg:fielImg
			}
			fc.close();
		}
		catch (Exception e) {}
	}
	
	public void animationEvent(int event) 
	{
		if( event == IAnimationEventListener.ANIMATION_STOPPED )
        {
            switch( this.animationType )
            {
            	case ANIMATION_OPEN:
            		this.state = STATE_OPENED;
            		this.animator.resetPosition( true );
            		break;
            	case ANIMATION_CLOSE:
            		this.state = STATE_CLOSED;
            		this.selectedItemIndex = 0;
            		this.animator.resetPosition( true );
            		if (dirState == STATE_NEXT_DIR)
            		{
            			updateFileList();
            			open();
            		}else if (dirState == STATE_SELECTED_FILE)
            		{
            			doWithFile(currDirName + currFileName);
            		}           			
            		
            		break;
            	case ANIMATION_SCROLL_DOWN:
            		this.animator.resetPosition(true);
            	case ANIMATION_SCROLL_UP:
            		this.animator.resetPosition(true);
            	break;
            }
        }
	}
	
	
	abstract void doWithFile(String _path);
}